// pages/search/search.js
import http from '../../utils/request';  // ✅ 改用封装后的请求模块

Page({
  data: {
    searchKeyword: '',     // 搜索关键词
    searchResults: [],     // 搜索结果列表
    hasSearched: false,    // 是否执行过搜索
    employeeNumber: '',    // 员工编号
    searchHistory: [],     // 搜索历史数据
    showHistory: false     // 控制历史面板显示
  },

  // ====================== 生命周期方法 ======================
  onLoad(options) {        // 从上级页面或全局数据获取员工编号
    const app = getApp();
    this.setData({
      employeeNumber: options.employeeNumber || app.globalData.employeeNumber
    });
    this.loadSearchHistory();// 加载本地存储的历史记录
  },

  // ====================== 搜索逻辑 ======================
  handleSearchInput: function(e) {// 实时搜索输入处理
    const keyword = e.detail.value.trim();
    this.setData({ 
      searchKeyword: keyword,
      showHistory: keyword === '' // 输入为空时显示历史记录
    });
    
    clearTimeout(this.searchTimer);// 防抖处理（300ms延迟
    this.searchTimer = setTimeout(() => {
      if (keyword) this.doSearch(keyword);
    }, 300);
  },

  async doSearch(keyword) {       // 执行搜索请求
    if (!keyword) return;

    try {
      wx.showLoading({ title: '搜索中...' });
      // ============== 接口改造开始 ==============
      const res = await http.get('/search_customers', {
        name: keyword,
        employee_number: this.data.employeeNumber
      });
      // ============== 接口改造结束 ==============

      console.log('[DEBUG] 原始响应数据:', res);

      // ✅ 适配新的响应结构
      if (res?.status === 'success') {
        const results = (res.data || []).map(item => ({
          ...item,
          formattedPhone: this.formatPhone(item.phone)
        }));
        
        this.setData({
          searchResults: results,
          hasSearched: true
        });

        this.saveSearchHistory(keyword);
      } else {
        throw new Error(res?.message || '搜索失败');
      }
    } catch (error) {
      console.error('[ERROR] 搜索失败:', error);
      wx.showToast({ 
        title: error.message || '请求异常',
        icon: 'none',
        duration: 2000
      });
    } finally {
      wx.hideLoading();
    }
  },

  // ====================== 历史记录管理 ======================
  loadSearchHistory() {      // 加载历史记录
    let history = wx.getStorageSync('searchHistory') || [];
    history = history.map(item => ({
      ...item,
      formattedTime: this._formatTimeFromStorage(item.timestamp)
    }));
    this.setData({ searchHistory: history });
  },

  saveSearchHistory(keyword) {
    let history = wx.getStorageSync('searchHistory') || [];
    history = history.filter(item => item.keyword !== keyword);
    history.unshift({
        keyword: keyword,
        timestamp: Date.now(),
        formattedTime: this._formatTime(Date.now())
    });
    if (history.length > 10) history.pop();
    wx.setStorageSync('searchHistory', history);
    this.setData({ searchHistory: history });
  },

  // ====================== 工具方法 ======================
  formatPhone(phone) {
    const clean = String(phone || '').replace(/\D/g, '');
    return clean.length >= 7 
      ? `${clean.slice(0,3)}****${clean.slice(-4)}` 
      : '未知号码';
  },

  // ====================== 交互方法 ======================
  handleCancel() {
    wx.navigateBack({ delta: 1 });
  },

  selectCustomer(e) {
    const customer = e.currentTarget.dataset.item;
    wx.navigateTo({
        url: `/pages/customer-card/customer-card?data=${encodeURIComponent(JSON.stringify(customer))}`
    });
  },

  onUnload() {
    clearTimeout(this.searchTimer);
  },

  searchFromHistory(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({ 
      searchKeyword: keyword,
      showHistory: false
    });
    this.doSearch(keyword);
  },

  clearHistory() {
    wx.removeStorageSync('searchHistory');
    this.setData({ searchHistory: [] });
    wx.showToast({ title: '已清空历史记录' });
  },

  showHistoryPanel() {
    this.setData({
      showHistory: true,
      hasSearched: false
    });
  },

  // ====================== 时间格式化 ======================
  _formatTime(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    
    if (date.toDateString() === now.toDateString()) {
      return date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit'
      });
    }
    
    const yesterday = new Date(now);
    yesterday.setDate(now.getDate() - 1);
    if (date.toDateString() === yesterday.toDateString()) {
      return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit'
      });
    }
    
    return `${date.getMonth()+1}月${date.getDate()}日`;
  },

  _formatTimeFromStorage(timestamp) {
    return timestamp.formattedTime || this._formatTime(timestamp);
  }
});